package se.plingapp.backingbeans;

import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import se.plingapp.enterprisebeans.CommentFacade;
import se.plingapp.enterprisebeans.MessageFacade;
import se.plingapp.entitybeans.Comment;
import se.plingapp.entitybeans.Content;
import se.plingapp.entitybeans.Message;
import se.plingapp.entitybeans.User;

/**
 * Comment backing bean.
 *
 * @author Erik Brännström
 */
@ManagedBean
@RequestScoped
public class CommentBean {

    @EJB
    private MessageFacade messageFacade;

    @EJB
    private CommentFacade commentFacade;

    private Long messageId;

    private Comment comment = new Comment();

    public Long getMessageId() {
        return this.messageId;
    }

    public void setMessageId(Long messageId) {
        this.messageId = messageId;
    }

    public Comment getComment() {
        return this.comment;
    }

    public void setComment(Comment comment) {
        this.comment = comment;
    }

    public List<Comment> getComments(Content m) {
        return commentFacade.findByContent(m);
    }

    public void create() {
        String id = FacesContext.getCurrentInstance().getExternalContext()
            .getRequestParameterMap().get("id");

        User activeUser = this.getActiveUser();
        this.comment.setUser(activeUser);
        this.comment.setContent(messageFacade.find(Long.parseLong(id)));
        this.commentFacade.create(this.comment);
        this.comment.setText("");
        this.comment = new Comment();
    }

    private User getActiveUser() {
        FacesContext fc = FacesContext.getCurrentInstance();
        return (User) fc.getExternalContext().getSessionMap().get("user");
    }
}
